package com.htfyun.fragment.read;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.OwnerSurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.htfyun.Constants;
import com.htfyun.HtfyunKdxfMainActivity;
import com.htfyun.ScanMyBooksDirManager;
import com.htfyun.utils.DebugLog;
import com.htfyun.utils.DisplayUtil;
import com.htfyun.view.EmptyRecyclerView;
import com.htfyun.view.GridSpacingItemDecoration;

import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.android.fbreader.covers.CoverManager;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.android.fbreader.util.AndroidImageSynchronizer;
import org.geometerplus.fbreader.Paths;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.BookEvent;
import org.geometerplus.fbreader.book.IBookCollection;
import org.geometerplus.fbreader.formats.PluginCollection;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.filetypes.FileType;
import org.geometerplus.zlibrary.core.filetypes.FileTypeCollection;
import org.geometerplus.zlibrary.ui.android.BuildConfig;
import org.geometerplus.zlibrary.ui.android.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by sst on 2017/11/21.
 */
public class ReadFragment extends SupportFragment {

    private EmptyRecyclerView mRecy;
    
    private ReadAdapter readAdapter;

    private View layoutReadingBook;
    private ImageView imgReadingBook;
    private TextView txtPagePercent;
    private TextView txtDate;
    private TextView txtBookTitle;
    private TextView txtBookAuthor;
    private ProgressBar progressBarPagePercent;
    
    
    private ImageView imgNext;
    private ImageView imgPrevious;
    private TextView txtPageNumberPercent;

    private int currentPage = 1;

    private final BookCollectionShadow myCollection = new BookCollectionShadow();

    private AndroidImageSynchronizer ImageSynchronizer;
    private CoverManager myCoverManager;

    public static ReadFragment newInstance() {

        Bundle args = new Bundle();

        ReadFragment fragment = new ReadFragment();
        fragment.setArguments(args);

     
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.htfyun_read_fragment, container, false);

        ImageSynchronizer = new AndroidImageSynchronizer(_mActivity);

        final int coverHeight = DisplayUtil.dipToPix(_mActivity, Constants.COVER_HEIGHT);
        final int coverWidth = DisplayUtil.dipToPix(_mActivity, Constants.COVER_WIDTH);

        myCoverManager = new CoverManager(_mActivity, ImageSynchronizer, coverWidth /*15 / 32*/, coverHeight);

        if (!BuildConfig.USE_PHONE) {
            view.setEinkUpdateMode((short)3, (short)3);
        }
        
        initView(view);
        return view;
    }

    private void initView(View view) {

        layoutReadingBook = view.findViewById(R.id.layoutReadingBook);
        layoutReadingBook.setVisibility(View.INVISIBLE);
        layoutReadingBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Object o = view.getTag();
                if (o instanceof Book) {
                    FBReader.openBookActivity(_mActivity, (Book)o, null);
                }
            }
        });
        imgReadingBook = (ImageView) view.findViewById(R.id.imgReadingBook);
        txtPagePercent = (TextView) view.findViewById(R.id.txtPagePercent);
        txtDate = (TextView) view.findViewById(R.id.txtDate);
//        txtDate.setVisibility(View.INVISIBLE);
        txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
        txtBookAuthor = (TextView) view.findViewById(R.id.txtBookAuthor);
        progressBarPagePercent = (ProgressBar) view.findViewById(R.id.progressBarPagePercent); 

        imgNext = (ImageView) view.findViewById(R.id.imgNext);
        imgPrevious = (ImageView) view.findViewById(R.id.imgPrevious);
        txtPageNumberPercent = (TextView) view.findViewById(R.id.txtPercent);

        imgNext.setOnClickListener(onClickListener);
        imgPrevious.setOnClickListener(onClickListener);
        
        mRecy = (EmptyRecyclerView) view.findViewById(R.id.recyclerView);

        View emptyView = view.findViewById(R.id.emptyView);
        mRecy.setEmptyView(emptyView);
        mRecy.setNestedScrollingEnabled(false);

//        final GridLayoutManager manager = new GridLayoutManager(_mActivity, 4, LinearLayoutManager.HORIZONTAL, false);
        final GridLayoutManager manager = new GridLayoutManager(_mActivity, 4);
        
        mRecy.setLayoutManager(manager);

        int space = getContext().getResources().getDimensionPixelSize(R.dimen.read_added_books_space);
        mRecy.addItemDecoration(new GridSpacingItemDecoration(4, space, true));

        readAdapter = new ReadAdapter(_mActivity);
        mRecy.setAdapter(readAdapter);

        configTxtPageNumberPercent();

        myCollection.bindToService(getContext(), new Runnable() {
            public void run() {
                myCollection.addListener(bookListener);
            }
        });
        
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        DebugLog.e("read fragment visible");
        initRecentReadingBook();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        
        myCollection.unbind();
    }

    private int getItemCountPerPage () {
        return getContext().getResources().getInteger(R.integer.read_book_count_per_page);
    }

    public List<File> getTotalItemList() {
        return ScanMyBooksDirManager.INSTANCE.getFiles();
    }
    private int getTotalPage() {
        int totalItem = 0;
        int itemCountPerPage = 1;
        if (getTotalItemList() != null) {
            totalItem = getTotalItemList().size();
        }

        if (getItemCountPerPage() > 0) {
            itemCountPerPage = getItemCountPerPage();
        }

        int totalPage = totalItem / itemCountPerPage;
        if (totalItem % itemCountPerPage != 0) {
            totalPage++;
        }

        return totalPage;

    }

    private void updateRecentReadingBookUI(Book book) {
        if (book == null) {
            return;
        }

        layoutReadingBook.setVisibility(View.VISIBLE);

        layoutReadingBook.setTag(book);
        if (!myCoverManager.trySetCoverImage(imgReadingBook, book, PluginCollection.Instance(Paths.systemInfo(_mActivity)))) {

            final FileType fileType = FileTypeCollection.Instance.typeForFile(ZLFile.createFileByPath(book.getPath()));
            DebugLog.e("fileTyp.id = " + fileType.Id);
            imgReadingBook.setImageResource(R.drawable.ic_shelf_txt);
            imgReadingBook.setBackgroundResource(R.drawable.shape_rect_bg);
        }

        txtBookAuthor.setText(book.authorsName());
        txtBookTitle.setText(book.getTitle());
        if (book.getProgress() != null) {

            txtPagePercent.setText(book.getProgress().Numerator + "/" + book.getProgress().Denominator);
            progressBarPagePercent.setMax((int) book.getProgress().Denominator);
            progressBarPagePercent.setProgress((int) book.getProgress().Numerator);
        }


        File file = new File(book.getPath());
        long time = file.lastModified();
        txtDate.setText(getDateTimeFromMillisecond(time));

    }
    private void initRecentReadingBook() {

            myCollection.bindToService(getContext(), new Runnable() {
                public void run() {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            
                            Book book = myCollection.getRecentBook(0);

                            updateRecentReadingBookUI(book);
                           
                        }
                    });
                }
            });
        
    }


    private void configTxtPageNumberPercent() {

        txtPageNumberPercent.setText(getString(R.string.base_page_number_percent, currentPage, getTotalPage()));
        txtPageNumberPercent.setVisibility(View.VISIBLE);

        int totalPage = getTotalPage();
        
        if (totalPage == 0 || totalPage == 1) {

            imgPrevious.setVisibility(View.INVISIBLE);
            imgNext.setVisibility(View.INVISIBLE);
            txtPageNumberPercent.setVisibility(View.INVISIBLE);

        } else if (currentPage == 1) {
            imgPrevious.setVisibility(View.INVISIBLE);
            imgNext.setVisibility(View.VISIBLE);

        } else if (currentPage == totalPage) {
            imgPrevious.setVisibility(View.VISIBLE);
            imgNext.setVisibility(View.INVISIBLE);
        } else {
            imgPrevious.setVisibility(View.VISIBLE);
            imgNext.setVisibility(View.VISIBLE);
        }
        configAdapter();

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            boolean changed = false;
            if (v == imgNext) {
                if (currentPage < getTotalPage()) {
                    currentPage++;
                    changed = true;
                }

            } else if (v == imgPrevious) {
                if (currentPage > 1) {
                    currentPage--;
                    changed = true;
                }

            }
            if (changed) {
                configTxtPageNumberPercent();
            }

        }
    };


    @SuppressWarnings("unchecked")
    private void configAdapter() {

        myCollection.bindToService(getContext(), new Runnable() {
            public void run() {
//                myCollection.addListener(bookListener);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        List<File> totalItems = getTotalItemList();
                        List<File> showItems = new ArrayList<>();
                        if (currentPage <= 0) {
                            currentPage = 1;
                        }
                        for (int index = (currentPage - 1) * getItemCountPerPage(), i = 0;
                             i < getItemCountPerPage() && index < totalItems.size(); index++, i++) {

                            showItems.add(totalItems.get(index));

                        }

                        List<Book> addedBooks = new ArrayList<>();


                        for (File bookFile : showItems) {
                            if (!bookFile.exists() || bookFile.isDirectory()) {
                                continue;
                            }


                            try {
                                long time = bookFile.lastModified();
                                String date = getDateTimeFromMillisecond(time);
                                DebugLog.e("date = " + date);

                            } catch (Exception e) {
                                DebugLog.e("error to get lastModified time");
                            }


                            Book myBook = myCollection.getBookByFile(bookFile.getPath());
                            if (myBook != null) {
                                addedBooks.add(myBook);
                            }
                        }

                        readAdapter.setItemsAndNotify(addedBooks);

                    }
                });
            }
        });

    }

    IBookCollection.Listener<Book> bookListener = new IBookCollection.Listener<Book>() {
        @Override
        public void onBookEvent(BookEvent event, Book book) {

            if (event == BookEvent.Opened) {
                updateRecentReadingBookUI(book);
                readAdapter.updateBook(book);
            }

//            myCollection.bindToService(getContext(), new Runnable() {
//                public void run() {
//                    myCollection.addListener(bookListener);
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            List<Book> recentBooks = myCollection.recentlyOpenedBooks(6);
//                            readAdapter.setDatas(recentBooks);
//                            readAdapter.notifyDataSetChanged();
//                        }
//                    });
//                }
//            });
            
        }

        @Override
        public void onBuildEvent(IBookCollection.Status status) {

        }
    };

    public static String getDateTimeFromMillisecond(long millisecond){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(millisecond);
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }
    

}
